#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <cstring>
using namespace std;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condA = PTHREAD_COND_INITIALIZER;
pthread_cond_t condB = PTHREAD_COND_INITIALIZER;
bool isA = true; // 状态变量，表示当前是否线程A执行

void* active(void* arg) {
    char* name = (char*)arg;

    while (true) {
        pthread_mutex_lock(&mutex);
        if (strcmp(name, "线程A") == 0) {
            while (!isA) { // 如果不是线程A的轮次，等待
                pthread_cond_wait(&condA, &mutex);
            }
            cout << "我是" << name << endl;
            sleep(1);
            isA = false; // 切换到线程B
            pthread_cond_signal(&condB); // 唤醒线程B
        } else {
            while (isA) { // 如果不是线程B的轮次，等待
                pthread_cond_wait(&condB, &mutex);
            }
            cout << "我是" << name << endl;
            sleep(1);
            isA = true; // 切换到线程A
            pthread_cond_signal(&condA); // 唤醒线程A
        }
        pthread_mutex_unlock(&mutex);
    }
    return nullptr;
}

int main() {
    pthread_t threadA, threadB;
    pthread_create(&threadA, nullptr, &active, (void*)"线程A");
    pthread_create(&threadB, nullptr, &active, (void*)"线程B");

    pthread_join(threadA, nullptr);
    pthread_join(threadB, nullptr);
    return 0;
}
